import { createElement } from './utils';
import type { ApiConfigItem } from '../types/config';

export function createApiConfigEditor(options: {
  mode: 'add' | 'edit';
  data?: ApiConfigItem;
  onSubmit: (item: ApiConfigItem) => void;
  onCancel: () => void;
}) {
  const { mode, data, onSubmit, onCancel } = options;
  
  // 创建编辑器容器
  const editor = createElement('div', {
    className: 'config-item editing'
  });

  // 初始化表单数据
  let form: ApiConfigItem = data ? JSON.parse(JSON.stringify(data)) : {
    target: '',
    replacement: '',
    headers: {},
    enabled: true,
    params: {},
    body: ''
  };

  // 构建编辑器HTML
  editor.innerHTML = `
    <div class="config-header">
      <div class="config-status">
        <label class="switch">
          <input type="checkbox" class="config-enabled" ${form.enabled ? 'checked' : ''}>
          <span class="slider"></span>
        </label>
      </div>
      <div class="config-urls">
        <input type="text" class="target-url" placeholder="目标接口地址" value="${form.target || ''}">
        <span class="arrow">→</span>
        <input type="text" class="replacement-url" placeholder="替换接口地址" value="${form.replacement || ''}">
      </div>
      <div class="config-actions">
        <button class="save-btn">保存</button>
        <button class="cancel-btn">取消</button>
      </div>
    </div>
    <div class="config-detail expanded">
      <div class="detail-section">
        <h4>请求参数</h4>
        <div class="param-list"></div>
        <button class="add-param-btn">+ 添加参数</button>
      </div>
      <div class="detail-section">
        <h4>请求头</h4>
        <div class="header-list"></div>
        <button class="add-header-btn">+ 添加请求头</button>
      </div>
      <div class="detail-section">
        <h4>请求体</h4>
        <textarea class="body-input" placeholder="请输入JSON格式的请求体...">${form.body || ''}</textarea>
      </div>
    </div>
  `;

  // 获取DOM元素
  const enabledInput = editor.querySelector('.config-enabled') as HTMLInputElement;
  const targetInput = editor.querySelector('.target-url') as HTMLInputElement;
  const replacementInput = editor.querySelector('.replacement-url') as HTMLInputElement;
  const paramList = editor.querySelector('.param-list') as HTMLElement;
  const headerList = editor.querySelector('.header-list') as HTMLElement;
  const bodyInput = editor.querySelector('.body-input') as HTMLTextAreaElement;
  const addParamBtn = editor.querySelector('.add-param-btn') as HTMLButtonElement;
  const addHeaderBtn = editor.querySelector('.add-header-btn') as HTMLButtonElement;
  const saveBtn = editor.querySelector('.save-btn') as HTMLButtonElement;
  const cancelBtn = editor.querySelector('.cancel-btn') as HTMLButtonElement;

  // 渲染参数列表
  function renderParams() {
    paramList.innerHTML = '';
    Object.entries(form.params || {}).forEach(([key, value]) => {
      const paramItem = createElement('div', { className: 'param-item' });
      paramItem.innerHTML = `
        <input type="text" class="param-name" placeholder="参数名" value="${key}">
        <input type="text" class="param-value" placeholder="参数值" value="${value}">
        <button class="delete-btn">删除</button>
      `;

      // 绑定事件
      const nameInput = paramItem.querySelector('.param-name') as HTMLInputElement;
      const valueInput = paramItem.querySelector('.param-value') as HTMLInputElement;
      const deleteBtn = paramItem.querySelector('.delete-btn') as HTMLButtonElement;

      let currentKey = key;

      // 使用 blur 事件代替 input 事件，在输入完成后才更新数据
      nameInput.addEventListener('blur', () => {
        if (form.params && currentKey !== nameInput.value) {
          const value = form.params[currentKey];
          delete form.params[currentKey];
          form.params[nameInput.value] = value;
          currentKey = nameInput.value;
        }
      });

      valueInput.addEventListener('blur', () => {
        if (form.params) {
          form.params[currentKey] = valueInput.value;
        }
      });

      // 处理回车键
      nameInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
          nameInput.blur();
        }
      });

      valueInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
          valueInput.blur();
        }
      });

      deleteBtn.addEventListener('click', () => {
        if (form.params) {
          delete form.params[currentKey];
          renderParams();
        }
      });

      paramList.appendChild(paramItem);
    });
  }

  // 渲染请求头列表
  function renderHeaders() {
    headerList.innerHTML = '';
    Object.entries(form.headers || {}).forEach(([key, value]) => {
      const headerItem = createElement('div', { className: 'header-item' });
      headerItem.innerHTML = `
        <div class="header-status">
          <label class="switch">
            <input type="checkbox" class="header-enabled" ${value.enabled ? 'checked' : ''}>
            <span class="slider"></span>
          </label>
        </div>
        <input type="text" class="header-name" placeholder="Header名" value="${key}">
        <input type="text" class="header-value" placeholder="值" value="${value.value}">
        <button class="delete-btn">删除</button>
      `;

      // 绑定事件
      const enabledInput = headerItem.querySelector('.header-enabled') as HTMLInputElement;
      const nameInput = headerItem.querySelector('.header-name') as HTMLInputElement;
      const valueInput = headerItem.querySelector('.header-value') as HTMLInputElement;
      const deleteBtn = headerItem.querySelector('.delete-btn') as HTMLButtonElement;

      let currentKey = key;

      enabledInput.addEventListener('change', () => {
        if (form.headers) {
          form.headers[currentKey] = {
            value: valueInput.value,
            enabled: enabledInput.checked
          };
        }
      });

      // 使用 blur 事件代替 input 事件
      nameInput.addEventListener('blur', () => {
        if (form.headers && currentKey !== nameInput.value) {
          const { value, enabled } = form.headers[currentKey];
          delete form.headers[currentKey];
          form.headers[nameInput.value] = { value, enabled };
          currentKey = nameInput.value;
        }
      });

      valueInput.addEventListener('blur', () => {
        if (form.headers) {
          form.headers[currentKey] = {
            value: valueInput.value,
            enabled: enabledInput.checked
          };
        }
      });

      // 处理回车键
      nameInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
          nameInput.blur();
        }
      });

      valueInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
          valueInput.blur();
        }
      });

      deleteBtn.addEventListener('click', () => {
        if (form.headers) {
          delete form.headers[currentKey];
          renderHeaders();
        }
      });

      headerList.appendChild(headerItem);
    });
  }

  // 初始渲染
  renderParams();
  renderHeaders();

  // 绑定事件
  enabledInput.addEventListener('change', () => {
    form.enabled = enabledInput.checked;
  });

  // 使用 blur 事件处理基本字段的更新
  targetInput.addEventListener('blur', () => {
    form.target = targetInput.value.trim();
  });

  replacementInput.addEventListener('blur', () => {
    form.replacement = replacementInput.value.trim();
  });

  bodyInput.addEventListener('blur', () => {
    form.body = bodyInput.value.trim();
  });

  // 处理回车键
  targetInput.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
      targetInput.blur();
    }
  });

  replacementInput.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
      replacementInput.blur();
    }
  });

  addParamBtn.addEventListener('click', () => {
    if (!form.params) form.params = {};
    const newKey = '';
    if (!(newKey in form.params)) {
      form.params[newKey] = '';
      renderParams();
    }
  });

  addHeaderBtn.addEventListener('click', () => {
    if (!form.headers) form.headers = {};
    const newKey = '';
    if (!(newKey in form.headers)) {
      form.headers[newKey] = { value: '', enabled: true };
      renderHeaders();
    }
  });

  saveBtn.addEventListener('click', () => {
    // 验证必填字段
    if (!form.target.trim() || !form.replacement.trim()) {
      alert('目标接口和替换接口不能为空');
      return;
    }

    // 验证参数名不能为空
    if (form.params) {
      const emptyParamKey = Object.keys(form.params).some(key => !key.trim());
      if (emptyParamKey) {
        alert('参数名不能为空');
        return;
      }
    }

    // 验证请求头名不能为空
    if (form.headers) {
      const emptyHeaderKey = Object.keys(form.headers).some(key => !key.trim());
      if (emptyHeaderKey) {
        alert('请求头名不能为空');
        return;
      }
    }

    onSubmit(form);
  });

  cancelBtn.addEventListener('click', onCancel);

  return editor;
} 